<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-05
 * Time: 12:12
 */

namespace App\Http\Middleware;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Shop;
use App\Models\User;
use App\Models\UserManager;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class TenantLogin extends Controller
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $accessToken = $request->header("accessToken");

        if (!$accessToken) {
            return $this->apiResponse('', config('errorLiu.PERMISSION_DENY'));
        }
        $manager = UserManager::select("*")->where("accessToken", $accessToken)->first();
        if (!$manager) {
            return $this->apiResponse('', config('errorLiu.PERMISSION_DENY'));
        }

        if(!$manager['status']){
            return $this->apiResponse('', config('errorLiu.MANAGER_NO_WUSIXAO'));
        }
        if($manager['isPlant']){
            $is_get= $request->isMethod('get');
            if(!$is_get){
                return $this->apiResponse('', config('errorLiu.GUANLIYUANSHIQULILANG'));
            }
            $shopId = $request->header("SHOPID");
            if(!$shopId){
                return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
            }
            $request->MANAGERID = $manager['managerId'];
            $request->SHOPID = $shopId;
            $request->ISPLANT = 1;
        }else{
            $mainShopId = Shop::where('shopId',$manager['shopId'])->value('mainShopId');
            if(!$mainShopId){
                $mainShopId = $manager['shopId'];
            }
            $forbiddenStatus = Shop::where('shopId',$mainShopId)->value('forbiddenStatus');
            if(!$forbiddenStatus){
                return $this->apiResponse('', config('errorLiu.DIANPUGUQOIQIZHANGTAIBU'));
            }
            $request->MANAGERID = $manager['managerId'];
            $request->SHOPID = $manager['shopId'];
            $request->ISPLANT = 0;
        }
        $request->pageSize = $request->pageSize ? $request->pageSize : 20;
        return $next($request);

    }

}

